package com.controller;

import com.bean.Admin;
import com.bean.Post;
import com.bean.User;
import com.db.AdminRepository;
import com.db.PostRepository;
import com.db.UserRepository;
import com.web.CookieTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;

/**
 * @author zhi keyan
 * @create 2020-12-11 21:34
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private PostRepository postRepository;

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String showAdminLogin(Model model){
        return "adminLogin";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String processAdminLogin(@RequestParam(value = "username", defaultValue = "") String username,
                                    @RequestParam(value = "password", defaultValue = "") String password, HttpSession session) throws UnsupportedEncodingException {
        boolean usernameisnull = false;
        boolean passwordisnull = false;
        String errormessage = "错误：";

        username = new String(username.getBytes("ISO-8859-1"),"utf-8");
        password = new String(password.getBytes("ISO-8859-1"),"utf-8");

        if(username.equals("") || username == null){
            usernameisnull = true;
            errormessage += " 用户名为空 ";
        }
        if(password.equals("") || password == null){
            passwordisnull = true;
            errormessage += " 密码为空 ";
        }
        if((!usernameisnull) && (!passwordisnull)){
            Admin admin = adminRepository.findByAdminName(username, password);
            System.out.println(username + "=====" + password);
            if(admin != null){
                session.setAttribute("admin", admin);
                return "redirect:/admin/homepage";
            }else {
                errormessage += " 用户名或密码错误 ";
                session.setAttribute("adminLoginErrorMessage", errormessage);
                return "adminLoginError";
            }
        }else{
            session.setAttribute("adminLoginErrorMessage", errormessage);
            return "adminLoginError";
        }
    }
    @RequestMapping(value = "homepage", method = RequestMethod.GET)
    public String showAdminHomepage(Model model){
        return "adminHomePage";
    }

    @RequestMapping(value = "adminList", method = RequestMethod.GET)
    public String showAdminList(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                Model model){

        model.addAttribute("adminList", adminRepository.findAdminPage(pageNo, pageSize));
        return "showAdminList";
    }

    @RequestMapping(value = "deleteAdmin/{adminID}", method = RequestMethod.GET)
    public String deleteAdmin(@PathVariable("adminID") int adminID ){
        Admin admin = adminRepository.findByAdminID(adminID);
        adminRepository.deleteAdmin(admin);
        return "redirect:/admin/adminList";
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String processAdminLogout(HttpSession session){
        session.removeAttribute("admin");
        session.invalidate();
        return "redirect:/admin/login";
    }


    @RequestMapping(value = "modify", method = RequestMethod.GET)
    public String showAdminModify(){
        return "adminModify";
    }

    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public String processAdminModify(@RequestParam(value = "username", defaultValue = "") String adminName,
                                     @RequestParam(value = "password", defaultValue = "") String password, HttpSession session) throws UnsupportedEncodingException {
        boolean usernameisnull = false;
        boolean passwordisnull = false;

        adminName = new String(adminName.getBytes("ISO-8859-1"),"utf-8");
        password = new String(password.getBytes("ISO-8859-1"),"utf-8");

        String errormessage = "修改信息失败：";
        System.out.println(adminName + "-----" + password);
        if(adminName.equals("") || adminName == null){
            usernameisnull = true;
            errormessage += " 管理员用户名为空 ";
        }
        if(password.equals("") || password == null){
            passwordisnull = true;
            errormessage += " 管理员密码为空 ";
        }

        if((!usernameisnull) && (!passwordisnull)){
            Admin admin = adminRepository.findByAdminName(adminName);
            if(admin == null){
                Admin sourceAdmin = (Admin)session.getAttribute("admin");

                Admin admin1 = adminRepository.adminModify(sourceAdmin, adminName, password);
                if(admin1 != null){
                    session.setAttribute("admin", admin1);
                    return "redirect:/admin/login";
                }else{
                    session.setAttribute("adminModifyErrorMessage", errormessage);
                    return "redirect:/admin/modify";
                }
            }else{
                errormessage += " 当前用户名已存在 ";
                session.setAttribute("adminModifyErrorMessage", errormessage);
                return "redirect:/admin/modify";
            }
        }else{
            session.setAttribute("adminModifyErrorMessage", errormessage);
            return "redirect:/admin/modify";
        }
    }

    @RequestMapping(value = "addAdmin", method = RequestMethod.GET)
    public String showAddAdmin(Model model){
        return "addAdmin";
    }

    @RequestMapping(value = "addAdmin", method = RequestMethod.POST)
    public String processAddAdmin(@RequestParam(value = "username", defaultValue = "") String username,
                                  @RequestParam(value = "password", defaultValue = "") String password,
                                  HttpSession session){
        boolean usernameisnull = false;
        boolean passwordisnull = false;
        String errormessage = "新增管理员失败：";
        System.out.println(username + "-----" + password);
        if(username.equals("") || username == null){
            usernameisnull = true;
            errormessage += " 管理员用户名为空 ";
        }
        if(password.equals("") || password == null){
            passwordisnull = true;
            errormessage += " 管理员密码为空 ";
        }
        if((!usernameisnull) && (!passwordisnull)){
            Admin admin = adminRepository.findByAdminName(username);
            if(admin == null){
                Admin newAdmin = new Admin(adminRepository.maxAdminID()+1, username, password, false);
                adminRepository.save(newAdmin);
                return "redirect:/admin/adminList";
            }else{
                errormessage += " 当前用户名已存在 ";
                session.setAttribute("addAdminErrorMessage", errormessage);
                return "redirect:/admin/addAdmin";
            }
        }else{
            session.setAttribute("addAdminErrorMessage", errormessage);
            return "redirect:/admin/addAdmin";
        }
    }

    @RequestMapping(value = "userList", method = RequestMethod.GET)
    public String showUserList(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                               @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                               Model model){
        model.addAttribute("userList", userRepository.findAllUserPage(pageNo, pageSize));
        return "showUserList";
    }

    @RequestMapping(value = "changeLock/{userID}", method = RequestMethod.GET)
    public String changeLock(@PathVariable(value = "userID") int userID){
        User user = userRepository.findByUserID(userID);
        userRepository.changeLock(user);
        return "redirect:/admin/userList";
    }

    @RequestMapping(value = "postList", method = RequestMethod.GET)
    public String showPostList(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                               @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                               Model model){
        model.addAttribute("postList", postRepository.findAllPostPage(pageNo, pageSize));
        return "showPostList";
    }

    @RequestMapping(value = "setTop/{postID}", method = RequestMethod.GET)
    public String setTop(@PathVariable(value = "postID") int postID){
        Post post = postRepository.findOne(postID);
        postRepository.setTop(post);
        return "redirect:/admin/postList";
    }

    @RequestMapping(value = "deletePost/{postID}", method = RequestMethod.GET)
    public String deletePost(@PathVariable(value = "postID") int postID){
        Post post = postRepository.findOne(postID);
        postRepository.deletePost(post);
        return "redirect:/admin/postList";
    }

    @RequestMapping(value = "editPost/{postID}", method = RequestMethod.GET)
    public String showEditPost(@PathVariable(value = "postID") int postID,
                               HttpSession session){
        Post post = postRepository.findOne(postID);
        session.setAttribute("updatePost", post);
        return "editPost";
    }

    @RequestMapping(value = "editPost/{postID}", method = RequestMethod.POST)
    public String processEditPost(@RequestParam(value = "topic", defaultValue = "") String topic,
                                  @RequestParam(value = "content", defaultValue = "") String context,
                                  @PathVariable(value = "postID") int postID,
                                  HttpSession session) throws UnsupportedEncodingException {
        boolean topicisnull = false;
        boolean contextisnull = false;
        String errorMessage = "编辑失败： ";

        topic = new String(topic.getBytes("ISO-8859-1"),"utf-8");
        context = new String(context.getBytes("ISO-8859-1"),"utf-8");
        System.out.println(topic);
        System.out.println(context);
        if((topic == null) || (topic.equals(""))){
            errorMessage += " 帖子主题为空 ";
            topicisnull = true;
        }
        if((context == null) || (context.equals(""))){
            errorMessage += " 帖子内容为空 ";
            contextisnull = true;
        }
        if((!topicisnull) && (!contextisnull)){
            Post post = postRepository.findOne(postID);
            Admin admin = (Admin)session.getAttribute("admin");
            postRepository.adminModifyPost(post,admin,topic,context);
            return "redirect:/admin/postList";
        }else{
            session.setAttribute("editPostErrorMessage", errorMessage);
            return "redirect:/admin/editPost/"+Integer.toString(postID);
        }
    }
}
